import tensorflow as tf
import numpy as np
# 一个例子

BATCH_SIZE = 8
seed = 23455
# tf_upgrade_v2 --infile v1.tf3_3.py --outfile v2.0.py
tf.compat.v1.disable_eager_execution() # 保证sess.run()能够正常运行

# 基于seed产生随机数
rng = np.random.RandomState(seed)
# 随机数返回32x2矩阵，表示32组数据
X = rng.rand(32,2)
# 构建Y标签，规定和为1为阈值，小于认为合格
Y = [[int(x0+x1<1)] for (x0,x1) in X]
print ("X:\n",X)
print ("Y:\n",Y)

# x = tf.constant([[0.7, 0.5]])
x = tf.compat.v1.placeholder(tf.float32,shape=(None,2))
y_ = tf.compat.v1.placeholder(tf.float32,shape=(None,1)) # 输出标签

w1 = tf.Variable( tf.compat.v1.random_normal([2,3], stddev=1, seed=1) )
w2 = tf.Variable( tf.compat.v1.random_normal([3,1], stddev=1, seed=1) )

# Forward Propagation
a = tf.matmul(x,w1) # 1st layer
y = tf.matmul(a,w2) # output

# 损失函数，反向传播
loss = tf.reduce_mean(tf.square(y_-y))
train_step = tf.compat.v1.train.GradientDescentOptimizer(0.001).minimize(loss)
# train_step = tf.train.MomentOptimizer(0.001, 0.9).minimize(loss)
# train_step = tf.train.AdamDescentOptimizer(0.001).minimize(loss)

with tf.compat.v1.Session() as sess:
    init_op = tf.compat.v1.global_variables_initializer() # 全局初始化参数，初始化节点
    sess.run(init_op)
    # print ( "y in tf3_3.py is : \n",sess.run(y) )
    # print ( "y in tf3_3.py is : \n",sess.run(y,feed_dict={x:[[0.7,0.5]]}) )
    
    # 打印出优化前参数
    print("w1:\n",sess.run(w1))
    print("w2:\n",sess.run(w2))
    print("\n")

    STEPS = 3000
    for i in range(STEPS):
        start = (i*BATCH_SIZE)%32
        end = start+BATCH_SIZE
        sess.run(train_step,feed_dict={x: X[start:end], y_:Y[start:end]})
        if i%500 ==0:
            total_loss = sess.run(loss,feed_dict = {x:X, y_:Y})
            print("训练 %d 步后，所有损失 %g" % (i,total_loss))
    
    # 训练后参数
    print("\n")
    print("w1:\n",sess.run(w1))
    print("w2:\n",sess.run(w2))